package ai4games_tests.maths;

import game2dai.maths.Geometry2D;
import processing.core.PApplet;

public class LineLineIntersection extends PApplet{

	final int IRAD = 5;
	float x0,y0,x1,y1,x2,y2,x3,y3;
	float[] ipoint = null;
	boolean intersect;

	public void setup(){
		size(400,300);
		smooth();
		cursor(CROSS);
		x0 = 83;
		y0 = 53;
		x1 = width - 118;
		y1 = height - 99;
		x2 = 30;
		y2 = height - 40; 
		intersect = false;
		ellipseMode(RADIUS);
	}

	public void draw(){
		background(128);
		x3 = mouseX;
		y3 = mouseY;
		intersect = Geometry2D.line_line(x0,y0,x1,y1,x2,y2,x3,y3);
		ipoint = makeFloatArray(Geometry2D.line_line_p(x0,y0,x1,y1,x2,y2,x3,y3));
		strokeWeight(1.2f);
		stroke(0,255,0);
		fill(255,240,240);
		if(intersect)
			stroke(255,0,0);
		line(x0,y0,x1,y1);
		line(x2,y2,x3,y3);
		
		fill(200,200,255);
		noStroke();
		for(int p = 0; p < ipoint.length; p += 2)
			ellipse(ipoint[p], ipoint[p+1], IRAD, IRAD);
		
		fill(255,255,0);
		if(ipoint.length == 0)
			text("No intersection", 10, height - 4);
		else
			text("Intersection at  "+ (int)ipoint[0]+", "+ (int)ipoint[1], 10,height - 4);	
	}

	public float[] makeFloatArray(double[] da){
		float[] fa = new float[da.length];
		for(int i = 0; i < fa.length; i++)
			fa[i] = (float)da[i];
		return fa;
	}
}
